package com.itheima.app.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.autoconfig.oss.OssTemplate;
import com.itheima.domain.db.Announcement;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Comment;
import com.itheima.domain.mongo.Movement;
import com.itheima.service.db.AnnouncementService;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.CommentService;
import com.itheima.service.mongo.MovementService;
import com.itheima.utils.ConstantUtil;
import com.itheima.utils.DateFormatUtil;
import com.itheima.vo.*;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Guanxing
 * @date 2021/9/22
 */
@Component
public class MovementManager {

    @Reference
    private MovementService movementService;

    @Autowired
    private OssTemplate ossTemplate;

    @Reference
    private UserInfoService userInfoService;

    @Reference
    private CommentService commentService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private MovementMQManager movementMQManager;

    //发布动态
    public void saveMovement(Movement movement, MultipartFile[] imageContent) throws IOException {
        ObjectId objectId = ObjectId.get();
        movement.setId(objectId);
        //创建集合用以存储文件
        List<String> medias = new ArrayList<>();
        //将图片上传到oss平台
        if (imageContent != null && imageContent.length > 0) {
            for (MultipartFile multipartFile : imageContent) {
                String path = ossTemplate.upload(multipartFile.getOriginalFilename(), multipartFile.getInputStream());
                medias.add("http://" + path);
            }
        }

        //获得userId
        Long userId = UserHolder.getId();
        //为move门头补充数据
        movement.setUserId(userId);
        movement.setMedias(medias);
        movement.setState(0);
        movement.setSeeType(1);
        //调用service
        movementService.saveMovement(movement);
        //发送mq消息
        rocketMQTemplate.convertAndSend("tanhua-movement",movement.getId().toHexString());
        //发布动态
        //movementMQManager.sendMsg(movement.getId().toHexString(),MovementMQManager.MOVEMENT_PUBLISH);
    }


    //根据id查询我的动态
    public PageBeanVo findMovementByUserId(Integer page, Integer pageSize, Long userId) {
        //分页查询我的动态
        PageBeanVo pageBeanVo = movementService.findMovementByUserId(page, pageSize, userId);

        //将返回值换成页面需要的返回值 数据搬家
        //创建页面需要的返回对象
        List<MovementVo> voList = new ArrayList<>();
        List<Movement> items = (List<Movement>) pageBeanVo.getItems();
        //数据转换
        for (Movement movement : items) {
            //构建一个vo对象
            MovementVo movementVo = new MovementVo();
            //用户数据
            UserInfo userInfo = userInfoService.findById(userId);

            //数据封装
            BeanUtil.copyProperties(userInfo, movementVo);
            BeanUtil.copyProperties(movement, movementVo);

            //手动封装
            if (StrUtil.isNotEmpty(userInfo.getTags())) {
                movementVo.setTags(userInfo.getTags().split(","));
            }
            if (CollectionUtil.isNotEmpty(movement.getMedias())) {
                movementVo.setImageContent(movement.getMedias().toArray(new String[]{}));
            }
            movementVo.setCreateDate(DateFormatUtil.format(new Date(movement.getCreated())));

            //设置点赞
            String key_liked = StrUtil.format(ConstantUtil.MOVEMENT_LIKE, UserHolder.getId(), movement.getId().toHexString());
            Boolean flag_liked = stringRedisTemplate.hasKey(key_liked);
            if (flag_liked) {
                movementVo.setHasLiked(1);
            }

            //设置喜欢
            String key_loved = StrUtil.format(ConstantUtil.MOVEMENT_LOVE, UserHolder.getId(), movement.getId().toHexString());
            Boolean flag_loved = stringRedisTemplate.hasKey(key_loved);
            if (flag_loved) {
                movementVo.setHasLoved(1);
            }

            if (movement.getState() == 1) {
                //将对象放入集合
                voList.add(movementVo);
            }
        }

        pageBeanVo.setItems(voList);
        return pageBeanVo;

    }

    //查询好友动态
    public PageBeanVo findFriendMovement(Integer page, Integer pageSize) {
        //获取当前用户id
        Long userId = UserHolder.getId();
        //根据当前用户id查询其朋友数据
        PageBeanVo pageBeanVo = movementService.findFriendMovement(page, pageSize, userId);
        //数据转换
        List<Movement> items = (List<Movement>) pageBeanVo.getItems();
        List<MovementVo> movementVoList = new ArrayList<>();

        //数据搬家
        if (CollectionUtil.isNotEmpty(items)) {
            for (Movement movement : items) {
                MovementVo movementVo = new MovementVo();
                //查询用户的数据
                UserInfo userInfo = userInfoService.findById(movement.getUserId());
                //封装数据
                movementVo.setUserInfo(userInfo);
                movementVo.setMovement(movement);

                //设置点赞
                String key_liked = StrUtil.format(ConstantUtil.MOVEMENT_LIKE, UserHolder.getId(), movement.getId().toHexString());
                Boolean flag_liked = stringRedisTemplate.hasKey(key_liked);
                if (flag_liked) {
                    movementVo.setHasLiked(1);
                }

                //设置喜欢
                String key_loved = StrUtil.format(ConstantUtil.MOVEMENT_LOVE, UserHolder.getId(), movement.getId().toHexString());
                Boolean flag_loved = stringRedisTemplate.hasKey(key_loved);
                if (flag_loved) {
                    movementVo.setHasLoved(1);
                }

                if (movement.getState() == 1) {
                    //放入集合
                    movementVoList.add(movementVo);
                }
            }
        }

        pageBeanVo.setItems(movementVoList);

        return pageBeanVo;
    }

    //查询推荐动态
    public PageBeanVo findRecommendMovement(Integer page, Integer pageSize) {
        //获取登录用户id
        Long loginUserId = UserHolder.getId();
        //调用查询
        PageBeanVo pageBeanVo = movementService.findRecommendMovement(page, pageSize, loginUserId);
        List<Movement> items = (List<Movement>) pageBeanVo.getItems();
        List<MovementVo> movementVoList = new ArrayList<>();
        //数据搬家
        if (CollectionUtil.isNotEmpty(items)) {
            for (Movement movement : items) {
                //查询每一个动态的用户信息
                UserInfo userInfo = userInfoService.findById(movement.getUserId());
                //封装数据
                MovementVo movementVo = new MovementVo();
                movementVo.setUserInfo(userInfo);
                movementVo.setMovement(movement);

                //设置点赞
                String key_liked = StrUtil.format(ConstantUtil.MOVEMENT_LIKE, UserHolder.getId(), movement.getId().toHexString());
                Boolean flag_liked = stringRedisTemplate.hasKey(key_liked);
                if (flag_liked) {
                    movementVo.setHasLiked(1);
                }

                //设置喜欢
                String key_loved = StrUtil.format(ConstantUtil.MOVEMENT_LOVE, UserHolder.getId(), movement.getId().toHexString());
                Boolean flag_loved = stringRedisTemplate.hasKey(key_loved);
                if (flag_loved) {
                    movementVo.setHasLoved(1);
                }

                if (movement.getState() == 1) {
                    //添加到集合
                    movementVoList.add(movementVo);
                }
            }
        }

        //返回数据
        pageBeanVo.setItems(movementVoList);
        return pageBeanVo;
    }

    //点赞
    public Integer commentLike(String publishId) {
        //获得当前用户id
        Long loginUserId = UserHolder.getId();
        Comment comment = new Comment();
        comment.setCreated(System.currentTimeMillis());
        comment.setPublishId(new ObjectId(publishId));
        comment.setCommentType(ConstantUtil.MOVEMENT_LIKE_1);
        comment.setUserId(loginUserId);
        //保存点赞操作
        Integer count = commentService.saveMovementComment(comment);

        String key = StrUtil.format(ConstantUtil.MOVEMENT_LIKE, loginUserId, publishId);
        stringRedisTemplate.opsForValue().set(key, "1");

        //点赞
        movementMQManager.sendMsg(publishId,MovementMQManager.MOVEMENT_LIKE);

        return count;
    }

    //取消点赞
    public Integer commentDisLike(String publishId) {
        //获得当前用户id
        Long loginUserId = UserHolder.getId();
        Comment comment = new Comment();
        comment.setCreated(System.currentTimeMillis());
        comment.setPublishId(new ObjectId(publishId));
        comment.setCommentType(ConstantUtil.MOVEMENT_LIKE_1);
        comment.setUserId(loginUserId);
        //取消点赞操作
        Integer count = commentService.deleteMovementComment(comment);

        String key = StrUtil.format(ConstantUtil.MOVEMENT_LIKE, loginUserId, publishId);
        stringRedisTemplate.delete(key);

        //取消点赞
        movementMQManager.sendMsg(publishId,MovementMQManager.MOVEMENT_DISLIKE);

        return count;
    }

    //动态喜欢
    public Integer saveMovementLove(String movementId) {
        //组装comment对象
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(ConstantUtil.MOVEMENT_LIKE_3);
        comment.setUserId(UserHolder.getId());

        //调用service
        Integer count = commentService.saveMovementComment(comment);

        //向redis中保存点赞标识
        String key = StrUtil.format(ConstantUtil.MOVEMENT_LOVE, UserHolder.getId(), movementId);
        stringRedisTemplate.opsForValue().set(key, "1");

        //喜欢
        movementMQManager.sendMsg(movementId,MovementMQManager.MOVEMENT_LOVE);

        return count;
    }

    //动态取消喜欢
    public Integer deleteMovementLove(String movementId) {
        //组装comment对象
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(ConstantUtil.MOVEMENT_LIKE_3);
        comment.setUserId(UserHolder.getId());

        Integer count = commentService.deleteMovementComment(comment);

        String key = StrUtil.format(ConstantUtil.MOVEMENT_LOVE, UserHolder.getId(), movementId);
        stringRedisTemplate.delete(key);

        //取消喜欢
        movementMQManager.sendMsg(movementId,MovementMQManager.MOVEMENT_DISLOVE);

        return count;
    }

    //单条动态
    public MovementVo findMovementVo(String movementId) {
        //查询动态详情
        Movement movement = movementService.findMovementByMovementId(movementId);

        //查询用户对象
        UserInfo userInfo = userInfoService.findById(movement.getUserId());

        //封装
        MovementVo movementVo = new MovementVo();
        movementVo.setUserInfo(userInfo);
        movementVo.setMovement(movement);

        //查询动态
        movementMQManager.sendMsg(movementId,MovementMQManager.MOVEMENT_BROWSE);

        return movementVo;
    }

    //评论列表
    public PageBeanVo findCommentList(Integer page, Integer pageSize, String movementId) {
        PageBeanVo pageBeanVo = commentService.findCommentList(page, pageSize, movementId);

        List<Comment> items = (List<Comment>) pageBeanVo.getItems();
        List<CommentVo> commentVoList = new ArrayList<>();

        //数据搬家
        if (CollectionUtil.isNotEmpty(items)) {
            for (Comment comment : items) {
                //查询评论人信息
                UserInfo userInfo = userInfoService.findById(comment.getUserId());
                //构建CommentVo对象
                CommentVo commentVo = new CommentVo();
                BeanUtil.copyProperties(userInfo, commentVo);
                BeanUtil.copyProperties(comment, commentVo);
                commentVo.setCreateDate(DateFormatUtil.format(new Date(comment.getCreated())));

                //放入集合
                commentVoList.add(commentVo);
            }
        }

        pageBeanVo.setItems(commentVoList);

        return pageBeanVo;
    }

    //发表评论
    public Integer saveComment(String movementId, String content) {
        //获取当前用户id
        Long loginUserId = UserHolder.getId();
        Comment comment = new Comment();
        comment.setCreated(System.currentTimeMillis());
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(ConstantUtil.MOVEMENT_LIKE_2);
        comment.setUserId(loginUserId);
        comment.setContent(content);
        //保存评论
        Integer count = commentService.saveMovementComment(comment);

        //评论动态
        movementMQManager.sendMsg( movementId  , MovementMQManager.MOVEMENT_COMMENT);

        return count;
    }

    //展示点赞 评论 喜欢
    public PageBeanVo messagesByCommentType(Integer page, Integer pageSize, int commentType) {
        PageBeanVo pageBeanVo = commentService.findMessagesByCommentType(page, pageSize, commentType, UserHolder.getId());

        List<Comment> items = (List<Comment>) pageBeanVo.getItems();
        List<UserCommentVo> userCommentVoList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(items)) {
            for (Comment comment : items) {
                //查询用户信息
                UserInfo userInfo = userInfoService.findById(comment.getUserId());
                //封装vo对象
                UserCommentVo userCommentVo = new UserCommentVo();
                BeanUtil.copyProperties(userInfo, userCommentVo);
                //转换日期
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:ss");
                userCommentVo.setCreateDate(simpleDateFormat.format(userInfo.getCreated()));
                //加入集合
                userCommentVoList.add(userCommentVo);
            }
        }

        pageBeanVo.setItems(userCommentVoList);
        return pageBeanVo;
    }
    //公告列表
    @Reference
    private AnnouncementService announcementService;

    public PageBeanVo messagesAnnouncements(Integer page, Integer pagesize) {
        PageBeanVo pageBeanVo = announcementService.messagesAnnouncements(page, pagesize);

        List<Announcement> announcementList = (List<Announcement>) pageBeanVo.getItems();

        List<AnnouncementVo> lists = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(announcementList)) {
            for (Announcement announcement : announcementList) {
                AnnouncementVo vo = new AnnouncementVo();
                //进行对象之间的属性赋值
                BeanUtil.copyProperties(announcement, vo);
                vo.setId(announcement.getId().toString());
                vo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(announcement.getCreated()));
                lists.add(vo);

            }
        }
        pageBeanVo.setItems(lists);

        return pageBeanVo;

    }

}
